/**
 * zmn渠道管理-列表
 * 文件命名格式：zmn.模块名称.表名称.功能.js
 * @author xiangjunming
 * @since 2019/08/22 18:07
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', 'formSelects', 'tooltipster', 'laytpl', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    let zmnSelect = layui.zmnSelect;
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    let formSelects = layui.formSelects;
    var tooltipster = layui.tooltipster;
    var laytpl = layui.laytpl;

    var data = {"code": 0, "msg": "", "count": json.totalCount};

    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        limit: json.pageSize,
        defaultToolbar: ['filter'],
        done: function (res, curr, count) {
            res.data.forEach((item, index) => {
                let channelId = Number(item.channelId);
                if (json.checkedIds.indexOf(channelId) != -1) {
                    res.data[index]["LAY_CHECKED"] = 'true';
                    $('tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                    $('tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');

                } else {
                    if (json.assChannelIds.indexOf(channelId) != -1) {
                        // 已管理了的渠道置灰 不能选中
                        $('tr[data-index=' + index + '] input[type="checkbox"]').prop('disabled', true);
                        $('tr[data-index=' + index + '] div a[id="assChannel"]').addClass('click-btn-color');
                        $('tr[data-index=' + index + '] div a[id="assChannel"]').prop('disabled', true);
                        $('tr[data-index=' + index + '] div a[id="assChannel"]').css("pointer-events", "none")
                        $('tr[data-index=' + index + ']').addClass('hide-channel-color');
                    }
                }
            });
        },
        height: 'full-280'
    });
    laypage.render(zmnPage.laypageOptions(json));

    // 修改排序
    table.on("edit(zmn-table)", function (obj) {
        zmnPage.laySort(obj, "/channel/updateSort.action", obj.data.channelId);
    });


    zmnSelect.selectOrganizeDeptTree('deptId', {
        selectedValues: [json.obj.deptId == null ? '' : json.obj.deptId],//回显值，格式：数组[depId1,depId2]
        remote: { //远程获取下拉数据
            enable: true, //开关：true-开启；false-关闭
            url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
        },
        events: {
            /**
             * 选择中事件
             * @param values 已选中值，Array类型
             */
            changing: function (values) {
                console.log("----------------------正选中的值:" + values);
            }
        }
    });

    zmnSelect.selectOrganizeDeptTree('abutmentDeptId', {
        selectedValues: [json.obj.abutmentDeptId == null ? '' : json.obj.abutmentDeptId],//回显值，格式：数组[depId1,depId2]
        remote: { //远程获取下拉数据
            enable: true, //开关：true-开启；false-关闭
            url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
        },
        events: {
            /**
             * 选择中事件
             * @param values 已选中值，Array类型
             */
            changing: function (values) {
                console.log("----------------------正选中的值:" + values);
            }
        }
    });

    // 平台所属组织下1级部门联动
    form.on('select(plat)', function (obj) {
        triggerOneDeptOptions(obj.value);
        triggerOneChannelOptions(obj.value);
    })

    // 故障价格表联动
    form.on('select(bizType)', function (obj) {
        triggerTariffOptions(obj.value);
    })

    form.on('select(servBizType)', function (obj) {
        triggerServPriceTableOptions(obj.value);
    })

    function triggerOneDeptOptions(value) {
        let oneDeptOptions = json.oneDepts.filter(p => p.orgId == value).map(p => {
            return p.deptId == json.obj.oneDeptId ? '<option value="' + p.deptId + '" selected="selected">' + p.deptName + '</option>' : '<option value="' + p.deptId + '">' + p.deptName + '</option>';
        });
        oneDeptOptions.unshift('<option value=""></option>');
        $('#oneDeptId').html(oneDeptOptions);
        form.render("select");
    }

    function triggerOneChannelOptions(plat, oneDeptId, deptId) {
        oneDeptId = zmnUtil.isEmptyNull(oneDeptId) ? null : oneDeptId;
        deptId = zmnUtil.isEmptyNull(deptId) ? null : deptId;
        let oneChannelOptions = json.oneChannels.filter(p => (plat == null || p.plat == plat) && (oneDeptId == null || p.oneDeptId == oneDeptId) && (deptId == null || p.deptId == deptId)).map(p => {
            return p.channelId == json.obj.parentId ? '<option value="' + p.channelId + '" selected="selected">' + p.name + '</option>' : '<option value="' + p.channelId + '">' + p.name + '</option>';
        });
        oneChannelOptions.unshift('<option value=""></option>');
        $('#parentId').html(oneChannelOptions);
        form.render("select");
    }

    function triggerTariffOptions(value) {
        let faultTariffOptions = json.faultTariffs.filter(p => (p.bizType == value && p.tariffType == 2)).map(p => {
            return p.tariffId == json.obj.tariffId ? '<option value="' + p.tariffId + '" selected="selected">' + p.tariffName + '</option>' : '<option value="' + p.tariffId + '">' + p.tariffName + '</option>';
        });
        faultTariffOptions.unshift('<option value=""></option>');
        $('#tariffId').html(faultTariffOptions);
        form.render("select");
    }

    function triggerServPriceTableOptions(value) {
        let faultTariffOptions = json.faultTariffs.filter(p => (p.bizType == value && p.tariffType == 1)).map(p => {
            return p.tariffId == json.obj.tariffId ? '<option value="' + p.tariffId + '" selected="selected">' + p.tariffName + '</option>' : '<option value="' + p.tariffId + '">' + p.tariffName + '</option>';
        });
        faultTariffOptions.unshift('<option value=""></option>');
        $('#servPriceId').html(faultTariffOptions);
        form.render("select");
    }


    if (json.obj.tariffId) {
        console.log('triggerTariffOptions')
        triggerTariffOptions(json.obj.bizType);
    }
    if (json.obj.servPriceId) {
        console.log('triggerServPriceTableOptions')
        triggerServPriceTableOptions(json.obj.bizType);
    }


    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        var data = obj.field;
        var url = "/channel/configInnerName.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            dataType: "json", data: data,
            success: function (resp) {
                var message = resp.status == 200 ? "操作成功！" : resp.message;
                layer.msg(message);
                // if(resp.status == 200) {
                //     zmnPage.reload(resp.message, 1000);
                // }
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });
        return false;
    });

    var channelId, obj;
    $("body").on("mouseover", ".btn-operate", event => {
        channelId = $(event.target).data("id");
        let index = $(event.target).data("index");
        obj = layui.table.cache["zmn-table"][index];
    });

    let ids = json.checkedIds;
    // 选择（全选或单选）
    table.on("checkbox(zmn-table)", function (obj) {
        ids = table.checkStatus('zmn-table').data.map((item) => item.channelId);
    });

    // 新增
    table.on("toolbar(zmn-table)", function (obj) {

        //启用停用
        if (obj.event !== "associate") {
            return false;
        }
        // 新增Id
        let addIds = ids.filter(function (x) {
            return json.checkedIds.indexOf(x) === -1;
        });
        // 取消渠道Id
        let delIds = json.showChannelIds.filter(function (x) {
            return json.checkedIds.indexOf(x) !== -1 && ids.indexOf(x) === -1;
        });
        if (addIds.length === 0 && delIds.length === 0) {
            return layer.alert("请选择至少1条数据！");
        }
        zmnPage.ajaxSimple("/channel/mark/modify/group/assChannels/update.action", {
            addIds: addIds.join(","),
            markId: json.mark.markId,
            delIds: delIds.join(",")
        }, 1000);
    });


    $(document).on('click', '#assChannel', function (e) {
        var channelId = $(this).attr("data-id");
        zmnPage.ajaxSimple("/channel/mark/modify/group/assChannels/update.action", {
            addIds: ""+channelId,
            markId: json.mark.markId
        }, 1000);
    });
    //对外暴露的接口
    exports('channel_mark_group_channel_list', {});
});